%{
#ifndef _BSD_SOURCE
#define _BSD_SOURCE
#endif

#include <string.h>
#include <stdlib.h>
//#include <stdarg.h>


//int fileno(FILE *stream);

#define YY_EXTRA_TYPE struct Buffer *

#define ECHO yyextra->y = yytext; while(*yyextra->y) *(yyextra->b++) = *(yyextra->y++)


struct Buffer {
	char *buf;
	char *b, *y;
	int has_data;
	size_t len;
//	int lineno, last_lineno;
};



%}

%option 8bit
%option extra-type="struct Buffer *"
%option noyywrap
%option reentrant

%x uri httpver header header1 header2 header3 data

%%

"GET "                  yyextra->has_data = 0; BEGIN(uri);
"POST "                 yyextra->has_data = 1; BEGIN(uri);

<uri>[^ \r\n]+          printf("uri: '%s'\n", yytext); BEGIN(httpver);
<httpver>[^\r\n]*\r?\n  BEGIN(header);
<header>"\r"?"\n"       if (yyextra->has_data) BEGIN(data); else yyterminate();
<header>[^:\r\n]+       printf("header name: '%s'\n", yytext); BEGIN(header1);
<header1>":"" "*        BEGIN(header2);
<header2>[^\r\n]+       printf("header value: '%s'\n", yytext); BEGIN(header3);
<header3>"\r"?"\n"      BEGIN(header);
<data>(.|\n)*           printf("DATA:\n%s\n", yytext); yyterminate();


%%


int http_process(char *buf, size_t len, FILE *stream) {
	struct Buffer *oB = (struct Buffer *)malloc(sizeof(struct Buffer));
	oB->has_data = 0;
	oB->buf = buf;
	oB->b = buf;
	oB->len = len;
//	oB->lineno = 1;
//	oB->last_lineno = 0;
		
	yyscan_t scanner;
	yylex_init(&scanner);

	yyset_extra(oB, scanner);
	yyset_in(stream, scanner);

	yylex(scanner);
	yylex_destroy(scanner);
}


main() {
	long len = 10000;
	char *buf = (char *)malloc(len + 1);
	*buf = 0;

	http_process(buf, len, stdin);
//	printf("\nREQUEST BODY:\n%s\n", buf);
}

